<?php
namespace app\common\command;
use OSS\OssClient;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\exception\ErrorException;
use think\facade\Env;

class BookCollect extends Command
{
    protected function configure()
    {
        $this->setName('book_collect')
            ->addArgument('action', Argument::OPTIONAL, "方法名称")
            ->setDescription('书籍内容采集');
    }

    protected function execute(Input $input, Output $output)
    {

        $action = $input->getArgument('action');
        $this->$action();

    }

    public function test22()
    {

        $list = Db::table('novel')->where('status','<','1')->select();
        foreach ($list as $v)
        {
            Db::table('novel_chapter')->where('novel_id',$v['id'])->delete();
            Db::table('novel_chapter_content_'. intval(substr($v['id'], -2)))->where('novel_id',$v['id'])->delete();
            Db::table('novel')->where('id',$v['id'])->delete();
        }
        for($i=2;$i<=99;$i++)
        {
            //$sql = "ALTER TABLE `quick_user_{$i}` CHANGE `userId` `device_id` VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL COMMENT '移动设备唯一标识'";
            //Db::execute($sql);
        }


    }

    public function import_txt()
    {
        $nig_gh = ['4751','4441','559','4248','659','142',252,4824,647,4816];
        foreach ($nig_gh as $nid)
        {
            $novel = Db::table('novel')->where('id',$nid)->field('origin_title')->findOrEmpty();
            $list = Db::table('novel_chapter_content_'.intval(substr($nid, -2)))->where('novel_id',$nid)
                ->order('chapter_no ASC')->field('content,chapter_no')->select();
            foreach ($list as $c)
            {
                $content = '第'.$c['chapter_no'].'章'."\r\n";
                $content .= $this->formatChapterContent($c['content'],"\r\n","\r\n");
                $path = Env::get('root_path').'public/uploads/'.$novel['origin_title'].".txt";
                file_put_contents($path,$content,FILE_APPEND);
            }
        }
    }

    public function test()
    {
        //$list = Db::table('cms_manager_user')->where('parent_id',2832)->field('id')->select();
        $agent_ids = Db::table('rp_recharge_rank_agent')->where('yesterday_new_amount','<',1)->column('agent_id');
        $list = Db::table('cms_manager_user')->where('parent_id','in',$agent_ids)->field('id,parent_id')->select();
        foreach ($list as $v)
        {
            $record = Db::table('pay_order_kl_config')->where('channel_id',$v['id'])->field('id')->findOrEmpty();
            if(!$record)
            {
                Db::table('pay_order_kl_config')->insert([
                    'agent_id'=>$v['parent_id'],'channel_id'=>$v['id'],'odds'=>0.3,'switch'=>1,'user_group'=>1,
                    'login_judg'=>0,'register_judg'=>1,'register_day'=>7
                ]);
            }
        }
    }

    /*
     * 快应用新系统数据采集
     * */
    public function quicknew()
    {
        $party_code = "quicknew";
        $url = "http://cpsht.xxingywl.cn/api/books";
        $url_c = "http://cpsht.xxingywl.cn/api/chapters";
        $result_json = doCurl($url);
        $result = json_decode($result_json,true);

        if($result['code'] == 0 && $result['data']) {

            foreach ($result['data'] as $book) {

                if($book['id'] <= 5264)
                {
                    continue;
                }

                $record = Db::table('novel_mp_party')->where('party_code',$party_code)
                            ->where('party_novel_id',$book['id'])->field('novel_id')->findOrEmpty();
                if($record)
                {
                    $nid = $record['novel_id'];
                    $max_chapter = Db::table('novel_chapter')->where('novel_id',$nid)->order('chapter_no DESC')
                                    ->field('chapter_no')->findOrEmpty();
                    $max_chapterorder = $max_chapter ? $max_chapter['chapter_no'] : 0;
                }else{
                    $verticpic = '';
                    if(strlen($book['cover']) > 1)
                    {
                        $savePath = 'quicknew/book/'.date('Ymd')."/".substr(md5(uniqid(rand())),-12).strrchr($book['cover'], '.');
                        $upload = $this->putfiletooss_product($savePath,$book['cover']);
                        if($upload['code']==0){
                            $verticpic = '/'.$savePath;
                        }
                    }

                    $data = [];
                    $data['title']          = $book['title'];
                    $data['origin_title']   = $book['origin_title'];
                    $data['cover']          = $verticpic;
                    $data['author']         = $book['author'];
                    $data['freq_id']        = $book['freq_id'];
                    $data['class_id']       = $book['class_id'];
                    $data['son_class_id']   = $book['son_class_id'];
                    $data['update_status']  = $book['update_status'];
                    $data['in_shelf']       = 0;
                    $data['scale']          = $book['scale'];
                    $data['brief']          = $book['brief'];
                    $data['number_words']   = $book['number_words'];

                    $nid = Db::table('novel')->insertGetId($data);
                    Db::table('novel_mp_party')->insert(['novel_id'=>$nid,'party_code'=>$party_code,'party_novel_id'=>$book['id']]);
                    $max_chapterorder = 0;
                }

                $page = 1;

                do{

                    $result_chapters = doCurl($url_c."?nid={$book['id']}&page={$page}&limit=500");
                    $result_chapters = json_decode($result_chapters,true);

                    if($result_chapters['code'] == 0 && $result_chapters['data']) {

                        foreach ($result_chapters['data'] as $vc) {

                            $time = time();

                            if ($vc['chapter_no'] > $max_chapterorder) {

                                Db::table('novel_chapter')->insert([
                                    'name'=>$vc['name'],'novel_id'=>$nid,'chapter_no'=>$vc['chapter_no'],
                                    'is_pay'=>$vc['is_pay'],'words'=>$vc['words']
                                ]);

                                $data_cc = [];
                                $data_cc['novel_id'] = $nid;
                                $data_cc['chapter_no'] = $vc['chapter_no'];
                                $data_cc['content'] = $vc['content'];
                                Db::table('novel_chapter_content_'. intval(substr($nid, -2)))->insert($data_cc);
                            }

                        }
                    }

                    $page++;

                }while(isset($result_chapters['data']) && $result_chapters['data']);

            }
        }

    }

    /*据点文学书籍采集*/
    public function judianwx()
    {
        $token = "1acdf1eadc9d2d89bda7cd1194404eab6003f0b8";
        $party_code = "judianwx";
        $url = "http://www.judianbook.com/index/api/BookList";
        $url_b = "http://www.judianbook.com/index/api/BookInfo";
        $url_c = "http://www.judianbook.com/index/api/BookChapters";
        $url_ct = "http://www.judianbook.com/index/api/BookChapterInfo";

        $result = doCurl($url."?p=1&size=1000&token={$token}");
        $result = json_decode($result,true);
        if($result['errcode'] == "200" && $result['data'])
        {
            foreach ($result['data'] as $book)
            {
                $record = Db::table('novel_mp_party')->where('party_novel_id',$book['bookid'])
                    ->where('party_code',$party_code)
                    ->field('novel_id')->findOrEmpty();

                $bookInfo = [];
                $result_b = doCurl($url_b."?token={$token}&book_id={$book['bookid']}");
                $result_b = json_decode($result_b,true);
                if($result_b['errcode'] == "200" && $result_b['data'])
                {
                    $bookInfo = $result_b['data'];
                }

                if(empty($bookInfo))
                {
                    continue;
                }

                if($record)
                {
                    $nid = $record['novel_id'];
                }else{

                    $verticpic = '';
                    if(strlen($bookInfo['cover']) > 1)
                    {
                        $savePath = 'quicknew/book/'.date('Ymd')."/".substr(md5(uniqid(rand())),-12).strrchr($bookInfo['cover'], '.');
                        $upload = $this->putfiletooss_product($savePath,$bookInfo['cover']);
                        if($upload['code']==0){
                            $verticpic = '/'.$savePath;
                        }
                    }

                    $cateogry = $this->categoryReplaceJudian($bookInfo['type']);
                    $data = [];
                    $data['title']          = $bookInfo['book_name'];
                    $data['origin_title']   = $bookInfo['book_name'];
                    $data['cover']          = $verticpic;
                    $data['author']         = $bookInfo['author'];
                    $data['freq_id']        = $cateogry['freq_id'];
                    $data['class_id']       = $cateogry['class_id'];
                    $data['son_class_id']   = 0;
                    $data['update_status']  = $bookInfo['state'];
                    $data['in_shelf']       = 0;
                    $data['scale']          = 'C';
                    $data['brief']          = $bookInfo['describe'];
                    $data['lead']           = $bookInfo['lead'];
                    $data['number_words']   = $bookInfo['word_number'];

                    $nid = Db::table('novel')->insertGetId($data);
                    Db::table('novel_mp_party')->insert(['novel_id'=>$nid,'party_code'=>$party_code,'party_novel_id'=>$book['bookid']]);
                }

                $page = 1;

                do{

                    $result_c = doCurl($url_c."?token={$token}&p={$page}&size=5000&book_id={$book['bookid']}");
                    $result_c = json_decode($result_c,true);

                    if($result_c['errcode'] == "200" && $result_c['data'])
                    {
                        foreach ($result_c['data'] as $chapter)
                        {
                            $data_c = [];
                            $data_c['name']         = $chapter['name'];
                            $data_c['novel_id']     = $nid;
                            $data_c['chapter_no']   = $chapter['chapnum'];
                            $data_c['is_pay']       = $chapter['is_pay'];
                            $data_c['words']        = $chapter['word_count'];

                            $record_c = Db::table('novel_chapter')->where('novel_id',$nid)
                                ->where('chapter_no',$chapter['chapnum'])->field('id')->findOrEmpty();

                            if(empty($record_c))
                            {
                                Db::table('novel_chapter')->insert($data_c);

                                $result_ct = doCurl($url_ct."?token={$token}&book_id={$book['bookid']}&chapnum={$chapter['chapnum']}");
                                $result_ct = json_decode($result_ct,true);
                                if($result_ct['errcode'] == "200")
                                {
                                    if(strlen($result_ct['content']) > 1)
                                    {
                                        $content = $this->formatChapterContent($result_ct['content'],"","\n");
                                    }else{
                                        $content = '';
                                    }

                                    $data_cc = [];
                                    $data_cc['novel_id'] = $nid;
                                    $data_cc['chapter_no'] = $chapter['chapnum'];
                                    $data_cc['content'] = $content;
                                    Db::table('novel_chapter_content_'. intval(substr($nid, -2)))->insert($data_cc);
                                }

                            }
                        }
                    }
                    $page++;
                }while($result_c['data']);

            }
        }

    }

    private function categoryReplaceJudian($cid)
    {
        $cat = [
            9=>['id'=>2,'channelid'=>1], 10=>['id'=>2,'channelid'=>1], 11=>['id'=>4,'channelid'=>1],
            13=>['id'=>11,'channelid'=>1], 14=>['id'=>22,'channelid'=>2], 21=>['id'=>13,'channelid'=>1],
            38=>['id'=>7,'channelid'=>1], 44=>['id'=>4,'channelid'=>1], 49=>['id'=>4,'channelid'=>1],
            2=>['id'=>20,'channelid'=>2], 3=>['id'=>21,'channelid'=>2], 4=>['id'=>21,'channelid'=>2],
            5=>['id'=>19,'channelid'=>2], 22=>['id'=>19,'channelid'=>2], 47=>['id'=>21,'channelid'=>2],
            48=>['id'=>21,'channelid'=>2], 20=>['id'=>5,'channelid'=>2], 40=>['id'=>5,'channelid'=>2],
            41=>['id'=>5,'channelid'=>2], 42=>['id'=>5,'channelid'=>2], 43=>['id'=>5,'channelid'=>2],
            24=>['id'=>23,'channelid'=>1], 25=>['id'=>23,'channelid'=>1], 26=>['id'=>23,'channelid'=>1],
            28=>['id'=>23,'channelid'=>1], 29=>['id'=>23,'channelid'=>1], 35=>['id'=>23,'channelid'=>1],
            36=>['id'=>23,'channelid'=>1]
        ];

        return ['class_id'=>$cat[$cid]['id'],'freq_id'=>$cat[$cid]['channelid']];
    }

    /*小程序接口*/
    public function applet()
    {
        $party_code = 'xiaochengxu';
        $url = "http://xcxht.jinqiwl.cn/api/books";
        $url_b = "http://xcxht.jinqiwl.cn/api/chapters?nid=";

        $result = doCurl($url);
        $result = json_decode($result,true);
        if($result['code'] == 0 && $result['data'])
        {
            foreach ($result['data'] as $book)
            {
                    $record = Db::table('novel_mp_party')->where('party_novel_id',$book['id'])
                        ->where('party_code',$party_code)
                        ->field('novel_id')->findOrEmpty();

                    if($record)
                    {
                        $nid = $record['novel_id'];
                    }else{

                        $verticpic = '';
                        if(strlen($book['cover']) > 1)
                        {
                            $savePath = 'quicknew/book/'.date('Ymd')."/".substr(md5(uniqid(rand())),-12).strrchr($book['cover'], '.');
                            $upload = $this->putfiletooss_product($savePath,$book['cover']);
                            if($upload['code']==0){
                                $verticpic = '/'.$savePath;
                            }
                        }

                        $data = [];
                        $data['title']          = $book['title'];
                        $data['origin_title']   = $book['title'];
                        $data['cover']          = $verticpic;
                        $data['author']         = $book['author'];
                        $data['freq_id']        = $book['freq_id'];
                        $data['class_id']       = 21;
                        $data['son_class_id']   = 0;
                        $data['update_status']  = $book['update_status'];
                        $data['in_shelf']       = 0;
                        $data['scale']          = $book['scale'];
                        $data['brief']          = $book['brief'];

                        $nid = Db::table('novel')->insertGetId($data);
                        Db::table('novel_mp_party')->insert(['novel_id'=>$nid,'party_code'=>$party_code,'party_novel_id'=>$book['id']]);
                    }

                    $page = 1;

                    do{

                        $result_c = doCurl($url_b.$book['id']."&page={$page}&limit=100");
                        $result_c = json_decode($result_c,true);
                        if($result_c['code'] == 0 && $result_c['data'])
                        {
                            foreach ($result_c['data'] as $chapter)
                            {
                                $data_c = [];
                                $data_c['name']         = $chapter['name'];
                                $data_c['novel_id']     = $nid;
                                $data_c['chapter_no']   = $chapter['chapter_no'];
                                $data_c['is_pay']       = $chapter['is_pay'];

                                $record_c = Db::table('novel_chapter')->where('novel_id',$nid)
                                    ->where('chapter_no',$chapter['chapter_no'])->field('id')->findOrEmpty();

                                if(empty($record_c))
                                {
                                    Db::table('novel_chapter')->insert($data_c);

                                    if(strlen($chapter['content']) > 1)
                                    {
                                        $content = $this->formatChapterContent($chapter['content'],"","\n");
                                    }else{
                                        $content = '';
                                    }

                                    $data_cc = [];
                                    $data_cc['novel_id'] = $nid;
                                    $data_cc['chapter_no'] = $chapter['chapter_no'];
                                    $data_cc['content'] = $content;
                                    Db::table('novel_chapter_content_'. intval(substr($nid, -2)))->insert($data_cc);

                                    Db::table('novel_chapter')->where('novel_id',$nid)
                                        ->where('chapter_no',$chapter['chapter_no'])->update(['words'=>count_word($content)]);
                                }else{

                                    if(strlen($chapter['content']) > 1)
                                    {
                                        $content = $this->formatChapterContent($chapter['content'],"","\n");
                                    }else{
                                        $content = '';
                                    }

                                    $data_cc = [];
                                    $data_cc['novel_id'] = $nid;
                                    $data_cc['chapter_no'] = $chapter['chapter_no'];
                                    $data_cc['content'] = $content;
                                    Db::table('novel_chapter_content_'. intval(substr($nid, -2)))
                                        ->where('novel_id',$nid)->where('chapter_no',$chapter['chapter_no'])->update($data_cc);

                                    Db::table('novel_chapter')->where('novel_id',$nid)
                                        ->where('chapter_no',$chapter['chapter_no'])->update(['words'=>count_word($content)]);
                                }
                            }
                        }
                        $page++;
                    }while($result_c['data']);

                    $words = Db::table('novel_chapter')->where('novel_id',$nid)->sum('words');
                    Db::table('novel')->where('id',$nid)->update(['chapter_up_time'=>date('Y-m-d H:i:s'),'number_words'=>$words]);

            }
        }
    }

    /*四维接口*/
    public function siwei()
    {
        $party_code = 'siwei';
        $url = "http://www.siweiip.com/api/ximei/booklist.php?appid=10858&apikey=20x2I3m1E1i13";
        $url_b = "http://www.siweiip.com/api/ximei/bookinfo.php?appid=10858&apikey=20x2I3m1E1i13&bookid=";
        $url_c = "http://www.siweiip.com/api/ximei/bookchapterinfo.php?appid=10858&apikey=20x2I3m1E1i13&bookid=";

        $result = doCurl($url);
        $result = json_decode($result,true);
        if(isset($result['data']['ids']))
        {
            foreach ($result['data']['ids'] as $party_novel_id)
            {

                if($party_novel_id <= 238725)
                {
                    continue;
                }

                $result_b = doCurl($url_b.$party_novel_id);
                $result_b = json_decode($result_b,true);
                if($result_b['data'])
                {
                    $record = Db::table('novel_mp_party')->where('party_novel_id',$party_novel_id)
                        ->where('party_code',$party_code)
                        ->field('novel_id')->findOrEmpty();

                    if($record)
                    {
                        $nid = $record['novel_id'];
                    }else{

                        $verticpic = '';
                        if(strlen($result_b['data']['bookPic']) > 1)
                        {
                            $savePath = 'quicknew/book/'.date('Ymd')."/".substr(md5(uniqid(rand())),-12).strrchr($result_b['data']['bookPic'], '.');
                            $upload = $this->putfiletooss_product($savePath,$result_b['data']['bookPic']);
                            if($upload['code']==0){
                                $verticpic = '/'.$savePath;
                            }
                        }

                        $sonClass = $this->getSonClassBySiwei($result_b['data']['classId']);

                        $data = [];
                        $data['title']          = $result_b['data']['name'];
                        $data['origin_title']   = $result_b['data']['name'];
                        $data['cover']          = $verticpic;
                        $data['author']         = $result_b['data']['author'];
                        $data['freq_id']        = $sonClass['freq_id'];
                        $data['class_id']       = $sonClass['class_id'];
                        $data['son_class_id']   = $sonClass['son_class_id'];
                        $data['update_status']  = $result_b['data']['isFull'];
                        $data['in_shelf']       = 0;
                        $data['scale']          = 'C';
                        $data['brief']          = $result_b['data']['intro'];

                        $nid = Db::table('novel')->insertGetId($data);
                        Db::table('novel_mp_party')->insert(['novel_id'=>$nid,'party_code'=>$party_code,'party_novel_id'=>$party_novel_id]);
                    }

                    $page = 1;

                    do{

                        $result_c = doCurl($url_c.$party_novel_id."&page={$page}&limit=100");
                        $result_c = json_decode($result_c,true);
                        if($result_c['data']['chapters'])
                        {
                            foreach ($result_c['data']['chapters'] as $chapter)
                            {
                                $data_c = [];
                                $data_c['name']         = $chapter['chapterName'];
                                $data_c['novel_id']     = $nid;
                                $data_c['chapter_no']   = $chapter['chapterOrder'];
                                $data_c['is_pay']       = $chapter['isVip'];

                                $record_c = Db::table('novel_chapter')->where('novel_id',$nid)
                                    ->where('chapter_no',$chapter['chapterOrder'])->field('id')->findOrEmpty();

                                if(empty($record_c))
                                {
                                    Db::table('novel_chapter')->insert($data_c);

                                    if(strlen($chapter['content']) > 1)
                                    {
                                        $content = $this->formatChapterContent($chapter['content'],"","\n");
                                    }else{
                                        $content = '';
                                    }

                                    $data_cc = [];
                                    $data_cc['novel_id'] = $nid;
                                    $data_cc['chapter_no'] = $chapter['chapterOrder'];
                                    $data_cc['content'] = $content;
                                    Db::table('novel_chapter_content_'. intval(substr($nid, -2)))->insert($data_cc);

                                    Db::table('novel_chapter')->where('novel_id',$nid)
                                        ->where('chapter_no',$chapter['chapterOrder'])->update(['words'=>count_word($content)]);
                                }else{

                                    if(strlen($chapter['content']) > 1)
                                    {
                                        $content = $this->formatChapterContent($chapter['content'],"","\n");
                                    }else{
                                        $content = '';
                                    }

                                    $data_cc = [];
                                    $data_cc['novel_id'] = $nid;
                                    $data_cc['chapter_no'] = $chapter['chapterOrder'];
                                    $data_cc['content'] = $content;
                                    Db::table('novel_chapter_content_'. intval(substr($nid, -2)))
                                        ->where('novel_id',$nid)->where('chapter_no',$chapter['chapterOrder'])->update($data_cc);

                                    Db::table('novel_chapter')->where('novel_id',$nid)
                                        ->where('chapter_no',$chapter['chapterOrder'])->update(['words'=>count_word($content)]);
                                }
                            }
                        }
                        $page++;
                    }while($result_c['data']['chapters']);

                    $words = Db::table('novel_chapter')->where('novel_id',$nid)->sum('words');
                    Db::table('novel')->where('id',$nid)->update(['chapter_up_time'=>date('Y-m-d H:i:s'),'number_words'=>$words]);

                }


            }
        }

    }

    private function getSonClassBySiwei($classId)
    {
        $arr = [
                3 => ['name'=>'恩怨情仇','freq_id'=>1], 4 => ['name'=>'异术超能','freq_id'=>1], 8 => ['name'=>'商战职场','freq_id'=>1],
                9 => ['name'=>'东方玄幻','freq_id'=>1], 10 => ['name'=>'异界争霸','freq_id'=>1], 12 => ['name'=>'远古神话','freq_id'=>1],
                13 => ['name'=>'古典仙侠','freq_id'=>1], 14 => ['name'=>'幻想修仙','freq_id'=>1], 15=>['name'=>'现代修仙','freq_id'=>1],
                16=>['name'=>'魔法校园','freq_id'=>1], 17=>['name'=>'西方奇幻','freq_id'=>1], 19=>['name'=>'亡灵异族','freq_id'=>1],
                21=>['name'=>'新派武侠','freq_id'=>1], 22=>['name'=>'架空历史','freq_id'=>1], 23=>['name'=>'网游竞技','freq_id'=>1],
                26=>['name'=>'星际争霸','freq_id'=>1], 29=>['name'=>'悬疑惊悚','freq_id'=>1], 32=>['name'=>'探险盗墓','freq_id'=>1],
                33=>['name'=>'末日复仇','freq_id'=>1], 34=>['name'=>'热血青春','freq_id'=>1], 36=>['name'=>'风水玄术','freq_id'=>1],
                37=>['name'=>'穿越时空','freq_id'=>1], 38=>['name'=>'都市娱乐','freq_id'=>1], 39=>['name'=>'现实文学','freq_id'=>1],
                40=>['name'=>'海外英文','freq_id'=>1],
                101=>['name'=>'穿越女强','freq_id'=>2],102=>['name'=>'重生复仇','freq_id'=>2],103=>['name'=>'宫闱宅斗','freq_id'=>2],
                104=>['name'=>'种田经商','freq_id'=>2],105=>['name'=>'古代言情','freq_id'=>2],106=>['name'=>'豪门总裁','freq_id'=>2],
                107=>['name'=>'重生娱乐','freq_id'=>2],108=>['name'=>'相爱职场','freq_id'=>2],109=>['name'=>'婚里婚外','freq_id'=>2],
                110=>['name'=>'菁菁校园','freq_id'=>2],111=>['name'=>'青梅竹马','freq_id'=>2],114=>['name'=>'都市言情','freq_id'=>2],
                117=>['name'=>'同人','freq_id'=>2],118=>['name'=>'灵异言情','freq_id'=>2],119=>['name'=>'复仇青春','freq_id'=>2],
                120=>['name'=>'娱乐明星','freq_id'=>2],129=>['name'=>'轻小说','freq_id'=>2],130=>['name'=>'玄幻修仙','freq_id'=>2],
                131=>['name'=>'网游竞技','freq_id'=>2],132=>['name'=>'诙谐搞笑','freq_id'=>2],122=>['name'=>'社会百态','freq_id'=>2],
                123=>['name'=>'经典读物','freq_id'=>2],124=>['name'=>'社科励志','freq_id'=>2],125=>['name'=>'出版小说','freq_id'=>2],
                126=>['name'=>'历史传记','freq_id'=>2],127=>['name'=>'名著散文','freq_id'=>2],128=>['name'=>'军事历史','freq_id'=>2]
            ];

        if(!isset($arr[$classId]))
        {
            return ['freq_id'=>0,'class_id'=>0,'son_class_id'=>0];
        }

        $info= $arr[$classId];

        if($info['name'] == '网游竞技')
        {
            $info['name'] = '网游电竞';
        }

        $son = Db::table('novel_class_son')->where('name',$info['name'])->findOrEmpty();
        if(empty($son))
        {
            return ['freq_id'=>0,'class_id'=>0,'son_class_id'=>0];
        }

        return ['freq_id'=>$son['freq_id'],'class_id'=>$son['class_id'],'son_class_id'=>$son['id']];
    }

    public function quick_old()
    {
        $url = "http://cpsht.ferietu.cn/admin/autoadd/getBooksOnline.html";
        $url_c = "http://cpsht.ferietu.cn/admin/autoadd/getchapterlist.html?nid=";
        $url_cc = "http://cpsht.ferietu.cn/admin/autoadd/getChapterContent?nid=";
        $result = doCurl($url);
        $result = json_decode($result,true);

        $quality = [0=>'C',1=>'B',2=>'A',3=>'S'];
        if($result['data'])
        {
            foreach ($result['data'] as $book)
            {
                if(!in_array($book['nid'],[4779,4781]))
                {
                    continue;
                }
                $record = Db::table('novel')->where('scale',$quality[$book['quality']])->where('origin_title',trim($book['name']))->field('id')->findOrEmpty();
                if(empty($record))
                {
                    $class_id = Db::table('novel_class')->where('name',$book['class'])->value('id');

                    $verticpic = '';
                    if(strlen($book['verticpic']) > 1)
                    {
                        $savePath = 'quicknew/book/'.date('Ymd')."/".substr(md5(uniqid(rand())),-12).strrchr($book['verticpic'], '.');
                        $upload = $this->putfiletooss_product($savePath,$book['verticpic']);
                        if($upload['code']==0){
                            $verticpic = '/'.$savePath;
                        }
                    }

                    $data = [];
                    $data['title']          = $book['ht_name'] ? $book['ht_name'] : $book['name'];
                    $data['origin_title']   = $book['name'];
                    $data['cover']          = $verticpic;
                    $data['author']         = $book['author'];
                    $data['freq_id']        = $book['channel'] == '男频' ? 1: 2;
                    $data['class_id']       = $class_id && $class_id > 0 ? $class_id : 0;
                    $data['son_class_id']   = 0;
                    $data['update_status']  = $book['fullflag'];
                    $data['in_shelf']       = 1;
                    $data['scale']          = $quality[$book['quality']];
                    $data['brief']          = $book['intro'];

                    $nid = Db::table('novel')->insertGetId($data);
                }else{
                    continue;
                    $nid = $record['id'];
                }

                $result_c = doCurl($url_c.$book['nid']);
                $result_c = json_decode($result_c,true);

                if($result_c['data']) {
                    foreach ($result_c['data'] as $chapter) {
                        $data_c = [];
                        $data_c['name']         = $chapter['chapter_title'];
                        $data_c['novel_id']     = $nid;
                        $data_c['chapter_no']   = $chapter['chapnum'];
                        $data_c['is_pay']       = $chapter['is_pay'];

                        $record_c = Db::table('novel_chapter')->where('novel_id',$nid)
                                ->where('chapter_no',$chapter['chapnum'])->field('id')->findOrEmpty();

                        if(empty($record_c))
                        {
                            Db::table('novel_chapter')->insert($data_c);

                            $result_cc = doCurl($url_cc.$book['nid'].'&cid='.$chapter['cid']);
                            $result_cc = json_decode($result_cc,true);
                            if(strlen($result_cc['data']) > 1)
                            {
                                $content = $this->formatChapterContent($result_cc['data'],"","\n");
                            }else{
                                $content = '';
                            }

                            $data_cc = [];
                            $data_cc['novel_id'] = $nid;
                            $data_cc['chapter_no'] = $chapter['chapnum'];
                            $data_cc['content'] = $content;
                            Db::table('novel_chapter_content_'. intval(substr($nid, -2)))->insert($data_cc);

                            Db::table('novel_chapter')->where('novel_id',$nid)
                                ->where('chapter_no',$chapter['chapnum'])->update(['words'=>count_word($content)]);
                        }else{
                            $result_cc = doCurl($url_cc.$book['nid'].'&cid='.$chapter['cid']);
                            $result_cc = json_decode($result_cc,true);
                            if(strlen($result_cc['data']) > 1)
                            {
                                $content = $this->formatChapterContent($result_cc['data'],"","\n");
                            }else{
                                $content = '';
                            }

                            $data_cc = [];
                            $data_cc['novel_id'] = $nid;
                            $data_cc['chapter_no'] = $chapter['chapnum'];
                            $data_cc['content'] = $content;
                            Db::table('novel_chapter_content_'. intval(substr($nid, -2)))
                                ->where('novel_id',$nid)->where('chapter_no',$chapter['chapnum'])->update($data_cc);

                            Db::table('novel_chapter')->where('novel_id',$nid)
                                ->where('chapter_no',$chapter['chapnum'])->update(['words'=>count_word($content)]);
                        }

                    }
                }

                $words = Db::table('novel_chapter')->where('novel_id',$nid)->sum('words');
                Db::table('novel')->where('id',$nid)->update(['chapter_up_time'=>date('Y-m-d H:i:s'),'number_words'=>$words]);

            }
        }

    }

    private function copyCover($org_url, $dir = 'book')
    {
        $absolute_root_path = Env::get('root_path');
        $absolute_path = $absolute_root_path . '/public/temp/'.$dir.'/';
        $file_name = substr($org_url, strrpos($org_url, '/') + 1, strlen($org_url));

        if (!file_exists($absolute_path)) {

            if (!mkdir($absolute_path, 0755, true)) {
                return '';
            }
        }

        try{
            $result = copy($org_url, $absolute_path . $file_name);
        }catch (ErrorException $e)
        {
            $result = '';
        }


        return $result ? '/public/temp/'.$dir.'/' . $file_name : '';
    }

    private function putfiletooss_product($filename,$filepath)
    {

        $path = $this->copyCover($filepath);

        if(strlen($path) < 1){
            return ['code'=>500,'msg'=>"error",'data'=>''];
        }

        $kv=array();
        $kv['AccessKeyID']      = config('oss_accessKeyID');
        $kv['AccessKeySecret']  = config('oss_accessKeySecret');
        $kv['OSS_ENDPOINT']     = config('oss_endPoint');
        $kv['OSS_BUCKET']       = config('oss_bucket');

        $ossClient = new OssClient($kv['AccessKeyID'], $kv['AccessKeySecret'], $kv['OSS_ENDPOINT']);
        $rs = $ossClient->uploadFile($kv['OSS_BUCKET'],$filename,Env::get('root_path').$path);

        if(isset($rs['oss-request-url'])){
            @unlink(Env::get('root_path').$path);
            return ['code'=>0,'msg'=>'success','data'=>$rs['oss-request-url']];
        }
        return ['code'=>500,'msg'=>"error",'data'=>''];
    }

    private function formatChapterContent($content,$start,$end)
    {
        $content_new = '';

        if (strlen($content) < 1)
        {
            return $content_new;
        }

        $content = str_replace("<p>","\n",$content);
        $content = str_replace("</p>","\n",$content);

        $list = explode("\n",$content);
        $list_new = '';
        foreach ($list as $k=>$v){

            if( $this->trim_space($v) ){
                $list_new .= $start.$this->trim_space($v).$end;
            }
        }

        return $list_new;

    }

    private function trim_space($content)
    {
        $content = trim(strip_tags($content));
        $content = preg_replace("/^".chr(194).chr(160)."+/","", $content);
        $content = preg_replace('# #', '', $content);
        $content = $this->removeIllegalChar($content);
        $search  = array(" ", "　", "\t", "\n", "\r", "&nbsp;");
        $replace = array("", "", "", "", "", "");

        return str_replace($search, $replace, $content);
    }

    private function removeIllegalChar($content)
    {
        if (is_string($content)) {

            $content = preg_replace("/[\\x00-\\x08\\x0b-\\x0c\\x0e-\\x1f]/", "", $content);

        } else if (is_array($content)) {

            foreach ($content as $k => $v) {
                $content[$k] = $this->removeIllegalChar($v);
            }

        }

        return $content;
    }

    public function refHtName(){
        $url = "http://cpsht.ferietu.cn/admin/autoadd/getBooksOnline.html";
        $result = doCurl($url);
        $result = json_decode($result,true);
        foreach ($result['data'] as $k => $v){
            if ($v['ht_name'] != '' && $v['name'] != $v['ht_name']){
                Db::table('novel')->where('origin_title',$v['name'])->setField("title",$v['ht_name']);
                echo $v['name'].PHP_EOL;
            }
        }
    }
}
